package cn.itsource._02_work_queue;

import com.rabbitmq.client.*;

import java.io.IOException;

//消息接受者
public class Rev2 {

    public static void main(String[] args) throws Exception {
        //1.通过连接工具创建链接对象
        Connection connection = cn.itsource._01_hello_world.ConnectionUtil.getConnection();

        //2.创建通道
        Channel channel = connection.createChannel();

        //4.声明队列：队列名，持久，独占链接，队列用完删除，扩展参数
        channel.queueDeclare(Send.NAME_QUEUE_WORK_QUEUE,true,false,false,null);

        //同时处理一个消息
        channel.basicQos(1);

        //5.接收消费的回调
        Consumer consumer = new  DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //int  i = 1 / 0 ;    //模拟消息消费中断
                System.out.println("消费者的ID："+consumerTag);
                System.out.println("消息的ID："+envelope.getDeliveryTag());
                System.out.println("交换机："+envelope.getExchange());
                System.out.println("队列："+envelope.getRoutingKey());
                System.out.println("收到消息："+new String(body));
                System.out.println("消息消费成功....................................");
                //手动签收消息
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        //6.接收并消费消息 : 队列名， 签收模式(true自动签收，false手动签收) ，回调
        channel.basicConsume(Send.NAME_QUEUE_WORK_QUEUE,false,consumer);
    }
}
